package com.yao.filter;

import com.alibaba.fastjson.JSONObject;
import com.yao.bean.R;
import org.codehaus.jackson.map.util.JSONPObject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/2 21:24
 * FileName: OauthLogoutFilter
 * Description:
 */

//@Component
public class OauthLogoutFilter extends OncePerRequestFilter implements InitializingBean, ApplicationContextAware {

    ConsumerTokenServices consumerTokenServices;

    ApplicationContext applicationContext;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getParameter("access_token");

        String requestURI = httpServletRequest.getRequestURI();
        httpServletResponse.setContentType("application/json;charset=utf-8");

        if(StringUtils.isEmpty(token)||!requestURI.equals("/oauth/logout")){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        if (consumerTokenServices.revokeToken(token)){
             httpServletResponse.getWriter().write(JSONObject.toJSONString(R.ok().data("成功")));
             return;
        }else{
             httpServletResponse.getWriter().write(JSONObject.toJSONString(R.err().data("失败")));
             return;
        }


    }

    @Override
    public void afterPropertiesSet(){
            this.consumerTokenServices=applicationContext.getBean(ConsumerTokenServices.class);

        Assert.notNull(this.consumerTokenServices,"ConsumerTokenServices cannot be null");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
